import { DataTypes } from 'sequelize';
import BaseModel from './BaseModel.js';

class Course extends BaseModel {
  static initModel(sequelize) {
    const attributes = {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      code: {
        type: DataTypes.STRING(20),
        allowNull: false,
        unique: true,
        validate: {
          notEmpty: true,
        },
      },
      name: {
        type: DataTypes.STRING(100),
        allowNull: false,
        validate: {
          notEmpty: true,
        },
      },
      description: {
        type: DataTypes.TEXT,
        allowNull: true,
      },
      credit: {
        type: DataTypes.FLOAT,
        allowNull: false,
        defaultValue: 2.0,
        validate: {
          min: 0.5,
          max: 10,
        },
      },
      capacity: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 30,
        validate: {
          min: 1,
          max: 500,
        },
      },
      currentEnrollment: {
        type: DataTypes.INTEGER,
        field: 'current_enrollment',
        defaultValue: 0,
        validate: {
          min: 0,
        },
      },
      location: {
        type: DataTypes.STRING(100),
        allowNull: true,
      },
      schedule: {
        type: DataTypes.STRING(100),
        allowNull: true,
        comment: '课程时间安排，如：周一 1-2节',
      },
      status: {
        type: DataTypes.TEXT,
        defaultValue: 'draft',
        validate: {
          isIn: [['draft', 'published', 'archived']]
        }
      },
      startDate: {
        type: DataTypes.DATEONLY,
        field: 'start_date',
        allowNull: true,
      },
      endDate: {
        type: DataTypes.DATEONLY,
        field: 'end_date',
        allowNull: true,
      },
      teacherId: {
        type: DataTypes.INTEGER,
        field: 'teacher_id',
        allowNull: false,
        references: {
          model: 'users',
          key: 'id',
        },
      },
    };

    const options = {
      // 钩子函数
      hooks: {
        beforeValidate: (course) => {
          // 确保当前选课人数不超过容量
          if (course.currentEnrollment > course.capacity) {
            throw new Error('当前选课人数不能超过课程容量');
          }
        },
      },
    };

    return super.init(sequelize, 'Course', attributes, options);
  }

  // 检查课程是否已满
  isFull() {
    return this.currentEnrollment >= this.capacity;
  }

  // 检查是否可以选课
  canEnroll() {
    return this.status === 'published' && !this.isFull();
  }

  // 定义关联关系
  static associate(models) {
    // 课程由教师教授
    this.belongsTo(models.User, {
      foreignKey: 'teacherId',
      as: 'teacher',
    });

    // 课程的选课记录
    this.hasMany(models.Enrollment, {
      foreignKey: 'courseId',
      as: 'enrollments',
    });
  }

  // 转换为JSON时添加额外字段
  toJSON() {
    const values = Object.assign({}, this.get());
    
    // 添加计算字段
    values.isFull = this.isFull();
    values.availableSeats = this.capacity - this.currentEnrollment;
    
    return values;
  }
}

export default Course;
